Convariant Return Type
Covariant Return Type
The covariant return type specifies that the return type may vary in the same direction as the subclass.
Before Java5, it was not possible to override any method by changing the return type. But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type. Let's take a simple example:
Note: If you are beginner to java, skip this topic and return to it after OOPs concepts.
Advantages of Covariant Return Type
Following are the advantages of the covariant return type.
- Covariant return type assists to stay away from the confusing type casts in the class hierarchy and makes the code more usable, readable, and maintainable.
- In the method overriding, the covariant return type provides the liberty to have more to the point return types.
- Covariant return type helps in preventing the run-time ClassCastExceptions on returns.